package com.miqtech.master.wyrecorder.ui;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.WYRecorderApp;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.entity.GiftAttachment;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.nim.NIMHelper;
import com.miqtech.master.wyrecorder.screenrecorder.services.PushStreamService;
import com.miqtech.master.wyrecorder.screenrecorder.share.ExpertMorePopupWindow;
import com.miqtech.master.wyrecorder.screenrecorder.share.ShareToFriendsUtil;
import com.miqtech.master.wyrecorder.ui.adapter.ChatRoomAdapter;
import com.miqtech.master.wyrecorder.user.UserProxy;
import com.miqtech.master.wyrecorder.utils.DeviceUtils;
import com.miqtech.master.wyrecorder.utils.DownloadImage;
import com.miqtech.master.wyrecorder.utils.L;
import com.miqtech.master.wyrecorder.utils.ListViewUtil;
import com.miqtech.master.wyrecorder.utils.LogCatHelper;
import com.miqtech.master.wyrecorder.utils.TimeUtils;
import com.miqtech.master.wyrecorder.utils.ToastUtils;
import com.miqtech.master.wyrecorder.widget.CustomDialog;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessageExtension;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tencent.tauth.Tencent;

import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by xiaoyi on 2016/7/27.
 * 录播activity
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)

public class ScreenRecorderActivity extends BaseAppCompatActivity  implements PushStreamService.PushStreamServiceListener{
    @BindView(R.id.tv_timer)
    TextView tvTimer;
    @BindView(R.id.img_bg)
    ImageView imgBg;
    @BindView(R.id.img_close_microphone)
    ImageView imgCloseMicrophone;
    ProgressDialog progressDialog;

    CustomDialog mCloseDialog;
    @BindView(R.id.img_share)
    ImageView imgShare;

    private PushStreamService mPushStreamService;
    private int mDensityDpi;

    private String gameIcon;
    private int mOrientation = 1;
    private int mVideoWidth = 960;
    private int mVideoHeight = 544;;
    Bundle data;
    private String gameId;
    private String liveTitle;
    private long mills = 0;
    private int requestLiveCount = 0;
    final int MSG_UPDATE_TIME = 0X8001;
    final int MSG_ENTER_CHATROOM = 0X8002;
    final int MSG_FINISH = 0X8003;
    final int MSG_LIVE_NOTIFY = 0X8004;
	final int MSG_LIVE_ERROR = 0X8005;
    private boolean isMute = false;
    private MediaProjectionManager mMediaProjectionManager = null;
    private MediaProjection mMediaProjection = null;
    private String pushParam = null;
    private String pushUrl = null;
	private long mEndPushTimes = 0;
    private boolean isStreaming = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_UPDATE_TIME:
                    mills += 1000;
                    tvTimer.setText(TimeUtils.formatTime(mills, "HH:mm:ss"));
                    break;
                case MSG_ENTER_CHATROOM:
                    enterChatRoom();
                    break;
                case MSG_LIVE_NOTIFY:
                    liveNotify();
                    break;
                case MSG_FINISH:
                    finish();
                    break;
				case MSG_LIVE_ERROR:
                    creatErrorDialog();
					break;
            }
        }
    };
    private ShareToFriendsUtil shareToFriendsUtil;//分享
    private ExpertMorePopupWindow popwin;//分享弹框

    /**
     * 聊天室相关
     */
    private ChatRoomAdapter mAdapter;
    @BindView(R.id.lvChat)
    ListView lvChat;
    List<Object> mMessageItems = new ArrayList<>();


    @Override
    public void initViews(Bundle savedInstanceState) {
	    //LogCatHelper.getInstance(WYRecorderApp.getContext()).start();
        data = getIntent().getExtras();
        if (savedInstanceState != null && data == null) {
            data = savedInstanceState;
        }
        if (data == null) return;
        parseDatas(data);
        getSize();
        Intent bindIntent = new Intent(WYRecorderApp.getContext(), PushStreamService.class);
        L.e(TAG, "startService");
        startService(bindIntent);
        bindService(bindIntent, conn, BIND_AUTO_CREATE);
        mAdapter = new ChatRoomAdapter(this, mMessageItems);
        lvChat.setAdapter(mAdapter);
    }


    private static final int REQUEST_CODE_SCREENCAPTURE = 1235;

    private void grantScreenCapturePermission() {
        Intent permissionIntent = mMediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(permissionIntent, REQUEST_CODE_SCREENCAPTURE);
    }
    private void creatErrorDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("娱儿手播")
                .setMessage("推流出现异常,请检查网络")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        close();
                    }
                }).create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 10103 || requestCode == 10104) {
            Tencent.onActivityResultData(requestCode, resultCode, intent, shareToFriendsUtil.getQQUIListener());
            return;
        }
        if (requestCode == REQUEST_CODE_SCREENCAPTURE) {
            if (resultCode == RESULT_OK && intent != null) {
                mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
                requestLive();
            } else {
                L.e(TAG, "request screen carture faild");
                close();
            }
        }
    }

    private void parseDatas(Bundle data) {
        mVideoHeight = data.getInt("videoHeight");
        mVideoWidth = data.getInt("videoWidth");
        mOrientation = data.getInt("screen");
        if (mOrientation == 0) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setContentView(R.layout.activity_screenrecorder);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setContentView(R.layout.activity_screenrecorder_land);
        }
        ButterKnife.bind(this);
        gameId = data.getString("gameId");
        liveTitle = data.getString("liveTitle");
        gameIcon = data.getString("gameIcon");
        popwin = new ExpertMorePopupWindow(this, R.style.Dialog);
        popwin.setOnItemClick(itemOnClick);
        shareToFriendsUtil = new ShareToFriendsUtil(this, popwin);

    }

    /**
     * 屏幕尺寸
     */
    private void getSize() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        mDensityDpi = metrics.densityDpi;
    }
        @Override
        public void onLiveStarted() {
            L.e(TAG, "onLiveStarted" );
            if (!isStreaming) {
				isStreaming = true;
                handler.sendEmptyMessage(MSG_ENTER_CHATROOM);
                Message msg = handler.obtainMessage(MSG_LIVE_NOTIFY);
                handler.sendMessageDelayed(msg, 2000);
            }
        }

        @Override
        public void onLiveError() {
            L.e(TAG, "onError()");
			handler.sendEmptyMessage(MSG_LIVE_ERROR);
        }

        @Override
        public void updateTime() {
            if (handler != null)
                handler.sendEmptyMessage(MSG_UPDATE_TIME);
        }

    /**
     * 采用绑定服务的方式
     * 将录屏推流的工作放在服务中
     */
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            L.e(TAG, "onServiceConnected");
            mPushStreamService = ((PushStreamService.PushStreamBinder) service).getService();
            if (mPushStreamService != null && isStreaming) {
                mills = mPushStreamService.getPushStreamTimes();
                handler.sendEmptyMessage(MSG_UPDATE_TIME);
            } else {
                mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                grantScreenCapturePermission();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            L.e(TAG, "===onServiceDisconnected=====");
			mPushStreamService = null;
			handler.sendEmptyMessage(MSG_LIVE_ERROR);
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        L.e(TAG, "===onnewintent=====");
        if (mPushStreamService != null) {
            mPushStreamService.setFloatChatViewVisible(false);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        L.e(TAG, "onStop");
        if (mPushStreamService != null && isStreaming) {
            mPushStreamService.setFloatChatViewVisible(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPushStreamService != null) {
            mPushStreamService.stopPushStream();
			mPushStreamService.stopService();
			unbindService(conn);
			mPushStreamService = null;
			mMediaProjection = null;
        }
        popwin = null;
        handler.removeCallbacksAndMessages(null);
        handler = null;
		fixInputMethodManagerLeak(this);
    }

    @OnClick({R.id.img_close, R.id.img_share, R.id.img_close_microphone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_close:
                showCloseDialog(1);
                break;
            case R.id.img_share:
                if (popwin != null) {
                    popwin.show();
                }
                break;
            case R.id.img_close_microphone:
                if (isMute) {
                    mPushStreamService.mute(false);
                    setMicrophoneIconState(false);
                    isMute = false;
                } else {
                    showCloseDialog(2);
                }
                break;
        }
    }

    public void close() {
		L.e(TAG, "close()  mPushStreamService = " + mPushStreamService);
        if (mPushStreamService != null) {
			mEndPushTimes = mPushStreamService.getPushStreamTimes();
            mPushStreamService.stopPushStream();
			mPushStreamService.stopService();
			unbindService(conn);
			mPushStreamService = null;
			mMediaProjection = null;
        }
		NIMHelper.getInstance().registeMessageObserver(messageReceiveObserver, false);
		isStreaming = false;
		Bundle data = new Bundle();
		data.putLong("mills", mEndPushTimes);
		data.putInt("screen", 0);
		jumpToActivity(LiveEndActivity.class, data);
		finish();
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        try {
            switch (method) {
                case API.LIVE_REQUEST:
                    requestLiveCount = 0;
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
                    pushParam = object.getString("object");
                    JSONObject pushParamObject = new JSONObject(pushParam);
                    boolean disable = pushParamObject.getBoolean("disabled");
                    String pushTitle = pushParamObject.getString("title");
                    String key = pushParamObject.getString("publishKey");
                    if (disable) {
                        ToastUtils.show("您已被禁播，请联系客服人员", 3000);
                        handler.sendEmptyMessageDelayed(MSG_FINISH, 3000);
                        return;
                    }
                    pushUrl = "rtmp://pili-publish.wangyuhudong.com/wyds/" + pushTitle + "?key=" + key;
                    //pushUrl = "rtmp://dl-publish.wangyuhudong.com/yetv/test123";
                    L.e(TAG, "pushUrl      " + pushUrl);
                    int mStatusHeight = DeviceUtils.deviceStatusHeight(this);
					mPushStreamService.setListener(this);
                    mPushStreamService.setPushStreamParams(mMediaProjection, mVideoWidth, mVideoHeight,mDensityDpi, pushUrl, mStatusHeight);
                    mPushStreamService.startPushStream();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFaild(JSONObject object, String method) {
        super.onFaild(object, method);
        errorHandle(method);
    }

    @Override
    public void onError(String errMsg, String method) {
        super.onError(errMsg, method);
        errorHandle(method);

    }

    private void errorHandle(String method) {
        switch (method) {
            case API.LIVE_REQUEST:
				L.e(TAG, "errorHandle()...requestLiveCount = " +requestLiveCount);
                /*when return faild,we will try 3 times again*/
                if (requestLiveCount < 3) {
                    requestLive();
                    requestLiveCount++;
                } else {
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
                    showToast("请求直播出错，请检查网络，然后退出重试");
                }
                break;
            case API.LIVE_NOTIFY:
                /*if live notify faild,notify again*/
                Message msg = handler.obtainMessage(MSG_LIVE_NOTIFY);
                handler.sendMessageDelayed(msg, 10000);
                break;
        }
    }

    /**
     * 通知后台设置参数
     */
    private void liveNotify() {
        L.e(TAG, "liveNotify()");
        User user = UserProxy.getUser();
        if (user != null) {
            Map<String, String> params = new HashMap<>();
            params.put("gameId", gameId);
            params.put("title", liveTitle);
            if (mOrientation == 0) {
                params.put("screen", "1");
            } else {
                params.put("screen", "0");
            }
            params.put("token", user.getToken());
            params.put("userId", user.getId());
            params.put("source", "1");
            sendHttpRequest(API.LIVE_NOTIFY, params);
        }
    }

    /**
     * 请求直播
     */
    private void requestLive() {
        L.e(TAG, "requestLive()");
        User user = UserProxy.getUser();
        if (user != null) {
            Map<String, String> params = new HashMap<>();
            params.put("token", user.getToken());
            params.put("userId", user.getId());
            sendHttpRequest(API.LIVE_REQUEST, params);
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            progressDialog.setMessage("连接中...");
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        L.e(TAG, "onResume");
        if (mPushStreamService != null) {
            mPushStreamService.showFloatActionButton(false);
            mPushStreamService.setFloatChatViewVisible(false);

        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        L.e(TAG, "onPause");
        if (mPushStreamService != null && isStreaming) {
            mPushStreamService.showFloatActionButton(true);
        }
    }

    @Override
    public void onBackPressed() {
        if (mPushStreamService != null && isStreaming) {
            moveTaskToBack(true);
        } else {
            super.onBackPressed();
        }
    }

    View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String sharetitle = "手游直播就上娱儿TV！";
            String sharecontent = "我在娱儿TV开播啦，求抱抱求围观求投食!";
//            String shareurl = API.HOST
////                    + API.LIVE_SHARE + id;
//                    + API.LIVE_SHARE + "";//原本应该传的是直播id，因为ios传的是主播id（已过审核），所以将错就错传主播id

            String shareurl = UserProxy.getUser().getShareUrl();
            String imgurl = API.IMAGE_HOST
                    + UserProxy.getUser().getIcon();
            switch (v.getId()) {
                case R.id.llSina:
                    shareToFriendsUtil.shareBySina(sharetitle, sharecontent, shareurl, imgurl);
                    break;
                case R.id.llWeChat:
                    shareToFriendsUtil.shareWyByWXFriend(sharetitle, sharecontent, shareurl, imgurl, 0);
                    break;
                case R.id.llFriend:
                    shareToFriendsUtil.shareWyByWXFriend(sharetitle, sharecontent, shareurl, imgurl, 1);
                    break;
                case R.id.llQQ:
                    shareToFriendsUtil.shareByQQ(sharetitle, sharecontent, shareurl, imgurl);
                    break;
            }
        }
    };

    View v;

    /**
     * @param type 1 关闭直播页面 2 关闭麦克风
     */
    private void showCloseDialog(final int type) {
        if (mCloseDialog == null) {
            mCloseDialog = new CustomDialog(this);

            //builder.setView(v)
            v = LayoutInflater.from(this).inflate(R.layout.layout_close_dialog, null);
        }
        mCloseDialog.show();
        Window w = mCloseDialog.getWindow();

        w.setBackgroundDrawableResource(android.R.color.transparent); // 设置对话框背景为透明
        w.setContentView(v);
        TextView tvUserId = (TextView) v.findViewById(R.id.tvUserId);
        TextView tvCancle = (TextView) v.findViewById(R.id.tvCancle);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCloseDialog.dismiss();
            }
        });
        TextView tvSure = (TextView) v.findViewById(R.id.tvSure);
        if (type == 1) {
            tvUserId.setText("确定要停止直播吗？");
        } else {
            tvUserId.setText("关闭麦克风后观众就听不到你的声音哦");
        }
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCloseDialog.dismiss();
                if (type == 1) {
                    close();
                } else {

                    if (mPushStreamService != null) {
                        mPushStreamService.mute(true);
                        setMicrophoneIconState(true);
                        isMute = true;
                    }

                }
            }
        });
    }

    /**
     * 设置麦克风图标状态
     *
     * @param isMute
     */
    private void setMicrophoneIconState(boolean isMute) {
        imgCloseMicrophone.setImageResource(isMute == true ? R.drawable.mirrophone_close : R.drawable.mirrophone_open);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        L.e(TAG, "onSaveInstanceState");
        super.onSaveInstanceState(outState);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        L.e(TAG, "--------onRestoreInstanceState-------");
        super.onRestoreInstanceState(savedInstanceState);

    }
	private  void fixInputMethodManagerLeak(Context destContext) {
		if (destContext == null) {	
			return;  
		}  
		  
		InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm == null) {	
			return;  
		}  
	  
		String [] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};  
		Field f = null;
		Object obj_get = null;	
		for (int i = 0;i < arr.length;i ++) {  
			String param = arr[i];	
			try{  
				f = imm.getClass().getDeclaredField(param);  
				if (f.isAccessible() == false) {  
					f.setAccessible(true);	
				} // author: sodino mail:sodino@qq.com	
				obj_get = f.get(imm);  
				if (obj_get != null && obj_get instanceof View) {  
					View v_get = (View) obj_get;  
					if (v_get.getContext() == destContext) {
						f.set(imm, null);
					} else {
						break;	
					}  
				}  
			}catch(Throwable t){  
				t.printStackTrace();  
			}  
		}  
	} 

    /**
     * 进入聊天室
     */
    private void enterChatRoom() {
        User u = UserProxy.getUser();
        if (u != null) {
            if (TextUtils.isEmpty(u.getChatRoomId())) {
                mMessageItems.add("创建直播聊天室异常，\n请在本次直播结束后退出登录重试!");
                mAdapter.notifyDataSetChanged();
                return;
            }
            mMessageItems.add("连接直播聊天室...");
            mAdapter.notifyDataSetChanged();

            EnterChatRoomData data = new EnterChatRoomData(u.getChatRoomId() + "");
            data.setNick(u.getNickname());
            data.setAvatar(u.getIcon());

            HashMap<String, Object> extension = new HashMap<String, Object>();
            extension.put("sex", u.getSex() + "");
            extension.put("isAnchor", "1");
            NIMHelper.getInstance().enterChatRoom(data, new RequestCallback() {
                @Override
                public void onSuccess(Object param) {
                    L.e(TAG, "enterChatRoom ------ success");
                    if (!mMessageItems.contains("连接直播聊天室成功"))
                        mMessageItems.add("连接直播聊天室成功");
                    mAdapter.notifyDataSetChanged();
                    NIMHelper.getInstance().registeMessageObserver(messageReceiveObserver, true);
                }

                @Override
                public void onFailed(int code) {
                    L.e(TAG, "enterChatRoom ------ faild " + code);
                    mMessageItems.add("连接直播聊天室失败(错误码" + code + (")"));
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onException(Throwable exception) {
                    L.e(TAG, "enterChatRoom ------ exception");
                    mMessageItems.add("连接直播聊天室错误");
                    mAdapter.notifyDataSetChanged();
                }
            });
        } else {
            mMessageItems.add("创建直播聊天室异常，\n请在本次直播结束后退出登录重试!");
        }
    }

    /**
     * 消息接受observer
     */
    Observer<List<ChatRoomMessage>> messageReceiveObserver = new Observer<List<ChatRoomMessage>>() {
        @Override
        public void onEvent(List<ChatRoomMessage> messages) {
            // 处理新收到的消息
            for (IMMessage message : messages) {
                MsgTypeEnum msgType = message.getMsgType();
                MsgAttachment attachment = message.getAttachment();
                if (attachment != null
                        && attachment instanceof ChatRoomNotificationAttachment
                        && (((ChatRoomNotificationAttachment) attachment).getType() == NotificationType.ChatRoomMemberExit)) {
                    continue;
                } else {
                    receiveMessage(message);
                }
            }
        }
    };

    /**
     * 处理收到消息
     *
     * @param message
     */
    private void receiveMessage(final IMMessage message) {
        if (message.getMsgType().getValue() == 10 && message.getAttachment() != null) {
            ChatRoomNotificationAttachment a = (ChatRoomNotificationAttachment) message.getAttachment();
            Log.i(TAG, "aaaa  " + a.getExtension());
        }
        Map<String, Object> extention = message.getRemoteExtension();
        if (extention != null && extention.size() >= 2) {
            if (extention.containsKey("robot")) {
                if (((Integer) extention.get("robot")) == 1) {
                    Log.i(TAG, "机器人发言过滤 ： " + extention.get("nickname"));
                    return;
                }
            } else if (extention != null && extention.containsKey("disable")) {  //禁播
                close();
                ToastUtils.show("由于您播放的内容不符合相关法律法规，已被禁播", 3000);

            }else if (extention.containsKey("mermaid")){  //美人鱼礼物过滤
                return;
            }
        }
        Log.i(TAG, "chat   " + ((ChatRoomMessage) message).getChatRoomMessageExtension().getSenderNick() + "------ " + message.getContent());
        mMessageItems.add(message);
        mAdapter.notifyDataSetChanged();
        if (!ListViewUtil.isLastMessageVisible(lvChat)) {
            ListViewUtil.scrollToBottom(lvChat);
        }

        if (mPushStreamService != null && mPushStreamService.getFloatTextView() != null) {
            getMessageContent(message, mPushStreamService.getFloatTextView());
        }
    }

    private void getMessageContent(IMMessage message, TextView tv) {
        ChatRoomMessage m = (ChatRoomMessage) message;
        String content = m.getContent();  //消息内容
        MsgAttachment attachment = m.getAttachment();  //消息附加
        Log.i(TAG, "content   =    " + content + "   name   " + message.getFromNick());
        String nickName = null;
        ChatRoomMessageExtension ce = m.getChatRoomMessageExtension();
        if (ce != null) {
            nickName = ce.getSenderNick();
        }
        if (TextUtils.isEmpty(nickName)) {
            if (message.getRemoteExtension() != null) {
                try {
                    nickName = message.getRemoteExtension().get("nickname").toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (attachment != null && TextUtils.isEmpty(nickName) && attachment instanceof ChatRoomNotificationAttachment) {
            ChatRoomNotificationAttachment a = (ChatRoomNotificationAttachment) attachment;
            nickName = a.getOperatorNick();
        }
        if (content == null) {   //content为空 表示 送礼物 进入聊天室
            if (message.getMsgType() == MsgTypeEnum.notification) {
                if (nickName == null)
                    if (message.getFromAccount().isEmpty()) {
                        nickName = "游客";
                    } else if (message.getFromAccount().toString().length() > 5) {
                        nickName = "游客" + message.getFromAccount().substring(0, 5);
                    } else {
                        nickName = "游客" + message.getFromAccount().toString();
                    }
                tv.setText(Html.fromHtml(getResources().getString(R.string.format_live_notify_enter_other, nickName)));
            } else {
                if (attachment != null && attachment instanceof GiftAttachment) {
                    initGiftMsg(message, tv);
                }
            }

        } else {  //content 不为空 表示发消息，机器人进入（伪  实际也是发消息）
            if (content.startsWith("欢迎") && content.endsWith("进入直播间") && TextUtils.isEmpty(nickName)) {
                content = content.replace("欢迎", "");
                content = content.replace("进入直播间", "");
                tv.setText(Html.fromHtml(getResources().getString(R.string.format_live_notify_enter_other, content)));
            } else {
                tv.setText(Html.fromHtml(getResources().getString(R.string.format_live_message, "" + nickName, "" + content)));
            }
        }
    }

    private void initGiftMsg(IMMessage message, TextView tv) {
        GiftAttachment attcachment = (GiftAttachment) message.getAttachment();
        String strGiftMessage;
        String senderName = attcachment.getSenderName() + " :  ";
        String giftName = "送给主播1个" + attcachment.getGiftName();
        String giftNumStr = "";
        String giftUrl = attcachment.getGiftShowImage();
        if (!TextUtils.isEmpty(attcachment.getGiftNum())) {
            int giftNum = Integer.parseInt(attcachment.getGiftNum());
            if (giftNum > 1) {
                giftNumStr = "  " + attcachment.getGiftNum() + "连击！";
                //                 giftHolder.tvGiftNum.setText(attcachment.getGiftNum() + "连击！");
            }
        }
        strGiftMessage = senderName + giftName + "G" + giftNumStr;
        SpannableStringBuilder builder = new SpannableStringBuilder(strGiftMessage);
        ForegroundColorSpan messageColor = new ForegroundColorSpan(getResources().getColor(R.color.gift_yellow));
        ForegroundColorSpan giftNumColor = new ForegroundColorSpan(getResources().getColor(R.color.orange));
        builder.setSpan(messageColor, 0, (senderName + giftName).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(giftNumColor, (senderName + giftName).length(), strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Drawable gift = new BitmapDrawable(getResources(), DownloadImage.getInstance().getBitmap(giftUrl));
        int size = DeviceUtils.dp2px(this, 10);
        gift.setBounds(0, 0, size, size);
        ImageSpan imageSpan = new ImageSpan(gift, ImageSpan.ALIGN_BASELINE);
        builder.setSpan(imageSpan, (senderName + giftName).length(), (senderName + giftName).length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        builder.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), (senderName + giftName).length() + 1, strGiftMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(builder);
    }
}
